package com.example.yskjproject.ui.activity;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.example.yskjproject.R;
import com.example.yskjproject.base.BaseActivity;
import com.example.yskjproject.content.EventContent;
import com.example.yskjproject.databinding.ActivityAreaAlertBinding;
import com.example.yskjproject.event.EventMessage;
import com.example.yskjproject.http.Urls;
import com.example.yskjproject.http.callback.JsonCallback;
import com.example.yskjproject.model.LzyResponse;
import com.example.yskjproject.utils.EventBusUtil;
import com.example.yskjproject.utils.GetJsonDataUtil;
import com.example.yskjproject.utils.JsonBean;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tencent.qcloud.tuicore.util.ToastUtil;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class AreaAlertActivity extends BaseActivity<ActivityAreaAlertBinding> {

    private List<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private ActivityAreaAlertBinding mActivityAreaAlertBinding;
    private FusedLocationProviderClient fusedLocationClient;
    private OptionsPickerView pvOptions;
    private String tx;
    private Gson gson = new Gson();

    @Override
    protected ActivityAreaAlertBinding getViewBinding() {
        // 初始化 ViewBinding
        mActivityAreaAlertBinding = ActivityAreaAlertBinding.inflate(LayoutInflater.from(this));
        return mActivityAreaAlertBinding;
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    showPickerView();
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    @Override
    protected void initData() {
        // 设置标题
        setTitle("选择地区");
        mActivityAreaAlertBinding.llArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initJsonData();
            }
        });
    }

    private void showPickerView() {// 弹出选择器

        pvOptions = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            //返回的分别是三个级别的选中位置
            String opt1tx = !options1Items.isEmpty() ?
                    options1Items.get(options1).getPickerViewText() : "";

            String opt2tx = !options2Items.isEmpty()
                    && !options2Items.get(options1).isEmpty() ?
                    options2Items.get(options1).get(options2) : "";

            String opt3tx = !options2Items.isEmpty()
                    && !options3Items.get(options1).isEmpty()
                    && !options3Items.get(options1).get(options2).isEmpty() ?
                    options3Items.get(options1).get(options2).get(options3) : "";

            tx = opt1tx + "." + opt2tx + "." + opt3tx;
        }).setLayoutRes(R.layout.area_picker, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        //自定义布局中的控件初始化及事件处理
                        TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        TextView ivCancel = v.findViewById(R.id.tv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvOptions.returnData();
                                mActivityAreaAlertBinding.tvCurrentAddress.setText(tx);
                                alertAreaInfo();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvOptions.dismiss();
                            }
                        });
                    }
                }).setTextXOffset(40, 40, 40)
                .setContentTextSize(36)
                .setLineSpacingMultiplier(3f)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void alertAreaInfo() {
        Map<String, Object> jsonParams = new HashMap<>();
        jsonParams.put("address", mBinding.tvCurrentAddress.getText().toString());
        String paramsDate = gson.toJson(jsonParams);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
        OkGo.<LzyResponse<Void>>post(Urls.UPDATE_USER).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse<Void>>() {
            @Override
            public void onSuccess(Response<LzyResponse<Void>> response) {
                ToastUtil.toastLongMessage("修改地区成功");
                EventMessage eventMessage = new EventMessage(EventContent.update_area, mBinding.tvCurrentAddress.getText().toString());
                EventBusUtil.sendEvent(eventMessage);
                finish();
            }

            @Override
            public void onError(Response<LzyResponse<Void>> response) {
                super.onError(response);
            }
        });
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCityList().get(c).getName();
                cityList.add(cityName);//添加城市
                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                /*if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    city_AreaList.add("");
                } else {
                    city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }*/
                city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList);

            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }
}
